﻿@model CustomerListModel
@using Telerik.Web.Mvc.UI;
@using System.Globalization;
@{
    var gridPageSize = EngineContext.Current.Resolve<Nop.Core.Domain.Common.AdminAreaSettings>().GridPageSize;
}
@using (Html.BeginForm())
{
    <div class="section-header">
        <div class="title">
            <img src="@Url.Content("~/Administration/Content/images/ico-customers.png")" alt="" />
            @T("Admin.Customers.Customers")
        </div>
        <div class="options">
            <a href="@Url.Action("Create")" class="t-button">@T("Admin.Common.AddNew")</a>
            <a href="@Url.Action("ExportXmlAll")" class="t-button">@T("Admin.Common.ExportToXml.All")</a>
            <button type="submit" id="exportxml-selected" class="t-button">@T("Admin.Common.ExportToXml.Selected")</button>
            <a href="@Url.Action("ExportExcelAll")" class="t-button">@T("Admin.Common.ExportToExcel.All")</a>
            <button type="submit" id="exportexcel-selected" class="t-button">@T("Admin.Common.ExportToExcel.Selected")</button>
        </div>
    </div>
    <table width="100%">
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.SearchCustomerRoleIds):
            </td>
            <td class="adminData">
                @foreach (var customerRole in Model.AvailableCustomerRoles)
                {
                    <input type="checkbox" name="SearchCustomerRoleIds" value="@customerRole.Id"
                @if (Model.SearchCustomerRoleIds != null && Model.SearchCustomerRoleIds.Contains(customerRole.Id))
                {
                    <text>checked="checked"</text>
                }
                />@customerRole.Name
                    <br />
                }
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.SearchEmail):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => Model.SearchEmail)
            </td>
        </tr>
        @if (Model.UsernamesEnabled)
        {
            <tr>
                <td class="adminTitle">
                    @Html.NopLabelFor(model => model.SearchUsername):
                </td>
                <td class="adminData">
                    @Html.EditorFor(model => Model.SearchUsername)
                </td>
            </tr>
        }
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.SearchFirstName):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => Model.SearchFirstName)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.SearchLastName):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => Model.SearchLastName)
            </td>
        </tr>
        @if (Model.DateOfBirthEnabled)
        {
            <tr>
                <td class="adminTitle">
                    @Html.NopLabelFor(model => model.SearchDayOfBirth):
                </td>
                <td class="adminData">
                    @{
            var monthOfBirthValues = new List<SelectListItem>();
            monthOfBirthValues.Add(new SelectListItem() { Text = T("Admin.Customers.Customers.List.SearchDateOfBirth.Month").Text, Value = "0" });
            for (int i = 1; i <= 12; i++)
            {
                monthOfBirthValues.Add(new SelectListItem() { Text = i.ToString(CultureInfo.InvariantCulture), Value = i.ToString(CultureInfo.InvariantCulture) });
            }
            var dayOfBirthValues = new List<SelectListItem>();
            dayOfBirthValues.Add(new SelectListItem() { Text = T("Admin.Customers.Customers.List.SearchDateOfBirth.Day").Text, Value = "0" });
            for (int i = 1; i <= 31; i++)
            {
                dayOfBirthValues.Add(new SelectListItem() { Text = i.ToString(CultureInfo.InvariantCulture), Value = i.ToString(CultureInfo.InvariantCulture) });
            }
                    }
                    @Html.DropDownListFor(model => Model.SearchMonthOfBirth, monthOfBirthValues)
                    @Html.DropDownListFor(model => Model.SearchDayOfBirth, dayOfBirthValues)
                </td>
            </tr>
        }
        
        @if (Model.CompanyEnabled)
        {
            <tr>
                <td class="adminTitle">
                    @Html.NopLabelFor(model => model.SearchCompany):
                </td>
                <td class="adminData">
                    @Html.EditorFor(model => Model.SearchCompany)
                </td>
            </tr>
        }        
        @if (Model.PhoneEnabled)
        {
            <tr>
                <td class="adminTitle">
                    @Html.NopLabelFor(model => model.SearchPhone):
                </td>
                <td class="adminData">
                    @Html.EditorFor(model => Model.SearchPhone)
                </td>
            </tr>
        }
        @if (Model.ZipPostalCodeEnabled)
        {
            <tr>
                <td class="adminTitle">
                    @Html.NopLabelFor(model => model.SearchZipPostalCode):
                </td>
                <td class="adminData">
                    @Html.EditorFor(model => Model.SearchZipPostalCode)
                </td>
            </tr>
        } 
        <tr>
            <td colspan="2">
                <button type="submit" id="search-customers" name="search-customers" value="search-customers" class="t-button">@T("Admin.Common.Search")</button>
            </td>
        </tr>
    </table>
    <p>
    </p>
    <table class="adminContent">
        <tr>
            <td>
                @(Html.Telerik().Grid<CustomerModel>(Model.Customers.Data)
                    .Name("customers-grid")
                    .ClientEvents(events => events.OnDataBound("onDataBound"))
                    .Columns(columns =>
                    {
                        columns.Bound(x => x.Id)
                        .Filterable(false)
                        .Template(x => string.Format("<input type='checkbox' name='checkedRecords' value='{0}' class='checkboxGroups'/>", x.Id))
                        .ClientTemplate("<input type='checkbox' name='checkedRecords' value='<#= Id #>' class='checkboxGroups'/>")
                        .Title("<input id='mastercheckbox' type='checkbox'/>")
                        .Width(50)
                        .HtmlAttributes(new { style = "text-align:center" })
                        .HeaderHtmlAttributes(new { style = "text-align:center" });

                        columns.Bound(x => x.Id)
                            .Width(50)
                            .Filterable(false);
                        //I don't know why but the customer list does not have an 'Edit' column in the grid on some machines (maybe because we are inside Html.BeginForm()).
                        //That's why the 'Email' column is clickable.
                        columns.Bound(x => x.Email)
                            .Template(x => Html.ActionLink(x.Email, "Edit", "Customer", new { id = x.Id }, new { }))
                            .ClientTemplate("<a href=\"" + @Url.Content("~/Admin/Customer/Edit/") + "<#= Id #>\"><#= Email #></a>")
                            .Width(150)
                            .Filterable(false);
                        //Weird!!! We can't pass Model.UsernamesEnabled to Hidden method
                        var usernameColumn = columns.Bound(x => x.Username)
                            .Width(150)
                            .Filterable(false);
                        if (!Model.UsernamesEnabled)
                            usernameColumn.Hidden(true);
                        columns.Bound(x => x.FullName)
                            .Width(200)
                            .Filterable(false);
                        columns.Bound(x => x.CustomerRoleNames)
                            .Width(200)
                            .Filterable(false);
                        //hidden column used for filtering
                        columns.Bound(x => x.SearchCustomerRoleIds)
                            .Width(5)
                            .Filterable(false)
                            .Hidden(true);
                        columns.Bound(x => x.SearchCustomerEmail)
                            .Width(5)
                            .Filterable(false)
                            .Hidden(true);
                        columns.Bound(x => x.SearchCustomerUsername)
                            .Width(5)
                            .Filterable(false)
                            .Hidden(true);
                        columns.Bound(x => x.SearchCustomerFirstName)
                            .Width(5)
                            .Filterable(false)
                            .Hidden(true);
                        columns.Bound(x => x.SearchCustomerLastName)
                            .Width(5)
                            .Filterable(false)
                            .Hidden(true);
                        columns.Bound(x => x.SearchCustomerDayOfBirth)
                            .Width(5)
                            .Filterable(false)
                            .Hidden(true);
                        columns.Bound(x => x.SearchCustomerMonthOfBirth)
                            .Width(5)
                            .Filterable(false)
                            .Hidden(true);
                        columns.Bound(x => x.SearchCustomerCompany)
                            .Width(5)
                            .Filterable(false)
                            .Hidden(true);
                        columns.Bound(x => x.SearchCustomerPhone)
                            .Width(5)
                            .Filterable(false)
                            .Hidden(true);
                        columns.Bound(x => x.SearchCustomerZipPostalCode)
                            .Width(5)
                            .Filterable(false)
                            .Hidden(true);
                        columns.Bound(x => x.Active)
                             .Width(100)
                             .Template(x => x.Active.ToString().ToLower())
                             .Centered()
                             .Filterable(false);
                        columns.Bound(x => x.CreatedOn)
                            .Width(100)
                            .Filterable(false);
                        columns.Bound(x => x.LastActivityDate)
                            .Width(100)
                            .Filterable(false);
                        columns.Bound(x => x.Id)
                            .Width(50)
                            .Centered()
                            .Template(x => Html.ActionLink(T("Admin.Common.Edit").Text, "Edit", new { id = x.Id }))
                            .ClientTemplate("<a href=\"Edit/<#= Id #>\">" + T("Admin.Common.Edit").Text + "</a>")
                            .Title(T("Admin.Common.Edit").Text)
                            .Filterable(false);
                    })
                    .Pageable(settings => settings.Total(Model.Customers.Total).PageSize(gridPageSize).Position(GridPagerPosition.Both))
                    .DataBinding(dataBinding => dataBinding.Ajax().Select("CustomerList", "Customer"))
                    .Filterable(filtering => filtering.Filters(filters =>
                    {
                        //customer role ids
                        if (!String.IsNullOrEmpty(ViewData["searchCustomerRoleIds"] as string))
                        {
                            filters.Add(x => x.SearchCustomerRoleIds).Contains((string)ViewData["searchCustomerRoleIds"]);
                        }
                        //customer email
                        if (!String.IsNullOrEmpty(ViewData["searchCustomerEmail"] as string))
                        {
                            filters.Add(x => x.SearchCustomerEmail).Contains((string)ViewData["searchCustomerEmail"]);
                        }
                        //customer username
                        if (!String.IsNullOrEmpty(ViewData["searchCustomerUsername"] as string))
                        {
                            filters.Add(x => x.SearchCustomerUsername).Contains((string)ViewData["searchCustomerUsername"]);
                        }
                        //customer first name
                        if (!String.IsNullOrEmpty(ViewData["searchCustomerFirstName"] as string))
                        {
                            filters.Add(x => x.SearchCustomerFirstName).Contains((string)ViewData["searchCustomerFirstName"]);
                        }
                        //customer last name
                        if (!String.IsNullOrEmpty(ViewData["searchCustomerLastName"] as string))
                        {
                            filters.Add(x => x.SearchCustomerLastName).Contains((string)ViewData["searchCustomerLastName"]);
                        }
                        //customer day of birth
                        if (!String.IsNullOrEmpty(ViewData["searchCustomerDayOfBirth"] as string))
                        {
                            filters.Add(x => x.SearchCustomerDayOfBirth).Contains((string)ViewData["searchCustomerDayOfBirth"]);
                        }
                        //customer month of birth
                        if (!String.IsNullOrEmpty(ViewData["searchCustomerMonthOfBirth"] as string))
                        {
                            filters.Add(x => x.SearchCustomerMonthOfBirth).Contains((string)ViewData["searchCustomerMonthOfBirth"]);
                        }
                        //customer company
                        if (!String.IsNullOrEmpty(ViewData["searchCustomerCompany"] as string))
                        {
                            filters.Add(x => x.SearchCustomerCompany).Contains((string)ViewData["searchCustomerCompany"]);
                        }
                        //customer phone
                        if (!String.IsNullOrEmpty(ViewData["searchCustomerPhone"] as string))
                        {
                            filters.Add(x => x.SearchCustomerPhone).Contains((string)ViewData["searchCustomerPhone"]);
                        }
                        //customer zip
                        if (!String.IsNullOrEmpty(ViewData["searchCustomerZipPostalCode"] as string))
                        {
                            filters.Add(x => x.SearchCustomerZipPostalCode).Contains((string)ViewData["searchCustomerZipPostalCode"]);
                        }
                    }))
                    .EnableCustomBinding(true))
            </td>
        </tr>
    </table>
    
    <script type="text/javascript">

        var selectedIds = [];

        $(document).ready(function () {

            $("#@Html.FieldIdFor(model => model.SearchEmail)").keydown(function (event) {
                if (event.keyCode == 13) {
                    $("#search-customers").click();
                    return false;
                }
            });
            $("#@Html.FieldIdFor(model => model.SearchFirstName)").keydown(function (event) {
                if (event.keyCode == 13) {
                    $("#search-customers").click();
                    return false;
                }
            });
            $("#@Html.FieldIdFor(model => model.SearchLastName)").keydown(function (event) {
                if (event.keyCode == 13) {
                    $("#search-customers").click();
                    return false;
                }
            });
            $("#@Html.FieldIdFor(model => model.SearchCompany)").keydown(function (event) {
                if (event.keyCode == 13) {
                    $("#search-customers").click();
                    return false;
                }
            });
            $("#@Html.FieldIdFor(model => model.SearchPhone)").keydown(function (event) {
                if (event.keyCode == 13) {
                    $("#search-customers").click();
                    return false;
                }
            });
            $("#@Html.FieldIdFor(model => model.SearchZipPostalCode)").keydown(function (event) {
                if (event.keyCode == 13) {
                    $("#search-customers").click();
                    return false;
                }
            });

            //"Export Excel selected" button
            $('#exportexcel-selected').click(function (e) {
                e.preventDefault();
                //redirect to required URL
                setLocation('@(Url.Action("ExportExcelSelected", "Customer"))?selectedIds=' + selectedIds.join(","));
                return false;
            });

            //"Export XML selected" button
            $('#exportxml-selected').click(function (e) {
                e.preventDefault();
                //redirect to required URL
                setLocation('@(Url.Action("ExportXmlSelected", "Customer"))?selectedIds=' + selectedIds.join(","));
                return false;
            });

            $('#mastercheckbox').click(function () {
                $('.checkboxGroups').attr('checked', $(this).is(':checked')).change();
            });

            //wire up checkboxes. 
            $('#customers-grid input[type=checkbox][id!=mastercheckbox]').live('change', function (e) {
                var $check = $(this);
                if ($check.is(":checked") == true) {
                    var checked = jQuery.inArray($check.val(), selectedIds);
                    if (checked == -1) {
                        //add id to selectedIds.  
                        selectedIds.push($check.val());
                    }
                }
                else {
                    var checked = jQuery.inArray($check.val(), selectedIds);
                    if (checked > -1) {
                        //remove id from selectedIds.  
                        selectedIds = $.grep(selectedIds, function (item, index) {
                            return item != $check.val();
                        });
                    }
                }
                updateMasterCheckbox();
            });
        });

        function onDataBound(e) {

            $('#customers-grid input[type=checkbox][id!=mastercheckbox]').each(function () {
                var currentId = $(this).val();
                var checked = jQuery.inArray(currentId, selectedIds);
                //set checked based on if current checkbox's value is in selectedIds.  
                $(this).attr('checked', checked > -1);
            });

            updateMasterCheckbox();
        }

        function updateMasterCheckbox() {
            var numChkBoxes = $('#customers-grid input[type=checkbox][id!=mastercheckbox]').length;
            var numChkBoxesChecked = $('#customers-grid input[type=checkbox][checked][id!=mastercheckbox]').length;
            $('#mastercheckbox').attr('checked', numChkBoxes == numChkBoxesChecked && numChkBoxes > 0);
        }
    </script>
@*<script type="text/javascript">
        $(document).ready(function () {
            $('#search-customers').click(function () {
                var grid = $('#customers-grid').data('tGrid');
                grid.currentPage = 1; //new search. Set page size to 1
                grid.ajaxRequest();
                return false;
            });
        });

        function onDataBinding(e) {
            //We need to use $.ajax({ data:{}, traditional:true });
            //See the following forum topic to get more info: http://forum.jquery.com/topic/jquery-1-4-breaks-asp-net-mvc-parameter-posting
            //But we don't have access to 'traditional' property passed by Telerik.

            if ($('[name=SearchCustomerRoleIds]:checked').size() > 0) {
                var customerRoleIds = [];
            }
            $('[name=SearchCustomerRoleIds]:checked').each(function () {
                customerRoleIds.push($(this).val());
            });

            var searchModel = {
                SearchCustomerRoleIds: customerRoleIds
            };
            e.data = searchModel;
        }
   </script>*@
}